/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.deployment.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;

import org.apache.xmlbeans.XmlCursor;

import cgl.narada.wsinfra.deployment.RoleRetriever;
import cgl.narada.wsinfra.deployment.ServiceMessageListener;
import cgl.narada.wsinfra.exception.DeploymentException;
import cgl.narada.wsinfra.exception.ProcessingException;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.addressing.FromDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.util.SoapEnvelopeConversion;
import cgl.narada.wsinfra.util.SoapMarshaller;
import cgl.narada.wsinfra.util.SoapMessageAlteration;
import cgl.narada.wsinfra.util.SoapPrinter;
import cgl.narada.wsinfra.wsa.WsaEnvelopeCreator;
import cgl.narada.wsinfra.wsa.WsaEprCreator;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;
import cgl.narada.wsinfra.wse.WseQNames;

public class SOAPClient implements ServiceMessageListener {

  private WsaEprCreator wsaEprCreator;
  private WsaEnvelopeCreator wsaEnvelopeCreator;
  private SoapEnvelopeConversion soapEnvelopeConversion;
  private SoapMessageAlteration soapMessageAlteration;
  private String sourceAddress;
  private int tracker;
  private WseQNames wseQNames;
  private String moduleName = "SOAPClient: ";

  public SOAPClient(String sourceAddress, String subManagerAddress)
    throws DeploymentException {
    this.sourceAddress = sourceAddress;
    
    wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();
    wsaEnvelopeCreator = WsaProcessingFactory.getWsaEnvelopeCreator();
    
    soapEnvelopeConversion = SoapEnvelopeConversion.getInstance();
    soapMessageAlteration = SoapMessageAlteration.getInstance();
    
    wseQNames = WseQNames.getInstance();
  }


  public void onMessage(SOAPMessage soapMessage) {
    System.out.println(moduleName + "Received SOAP Message from the " +
		       "underlying infrastructure");
    printSoapMessage(soapMessage);
  }


  public void onException(Exception exception) {

  }


  public void printSoapMessage(SOAPMessage soapMessage) {
    String soapMsg = null;
    try {
      soapMsg = SoapPrinter.getStringRepresentation(soapMessage);
    } catch (Exception e) {
      System.out.println(moduleName + "Problems printing SOAPMessage"); 
    }
    System.out.println(soapMsg);
  }




  private EnvelopeDocument createEnvelopeDocument() {
    EndpointReferenceType sourceEpr = wsaEprCreator.createEpr(sourceAddress);
    FromDocument from = FromDocument.Factory.newInstance();
    from.setFrom(sourceEpr);
    EnvelopeDocument envelopeDocument = 
      wsaEnvelopeCreator.createSoapEnvelope(from);
    QName qname = new QName("http://www.naradabrokering.org", 
			    "Application-Content");
    String qnameValue = "Tracker (" + tracker + ")";
    String actorAttributeValue = "http://www.naradabrokering.org/logging";
    soapMessageAlteration.
      addToSoapHeaderWithActorAttribute(envelopeDocument, qname, qnameValue,
					actorAttributeValue);
							    
    QName qnameCounter = new QName("http://www.naradabrokering.org", 
				   "Counter-Stuff");
    String qnameCounterValue = System.currentTimeMillis() + "";
    String actorAttributeValue2 = "http://www.naradabrokering.org/counter";
    soapMessageAlteration.
      addToSoapHeaderWithActorAttribute(envelopeDocument, 
					qnameCounter, qnameCounterValue,
					actorAttributeValue2);


    /*XmlCursor headerCursor = 
      envelopeDocument.getEnvelope().getHeader().newCursor();
      headerCursor.push();
      
      headerCursor.toNextToken();
      headerCursor.insertElementWithText(qname, "Tracker (" + tracker + ")");
      
      
      headerCursor.pop();
      headerCursor.toNextToken();
      headerCursor.toNextToken();
      QName actorQName = 
      new QName("http://schemas.xmlsoap.org/soap/envelope/", "actor");

      headerCursor.insertAttributeWithValue(actorQName, "http://www/logging");
      headerCursor.dispose();
    */
   
    XmlCursor bodyCursor = 
      envelopeDocument.getEnvelope().getBody().newCursor();
    tracker++;
    String value = "Tracker :" + tracker + "\n" +
      "The quick brown fox jumps upon the lazy dog";
    bodyCursor.toNextToken();

    String catUri = "http://www.naradabrokering.org/catalog";
    bodyCursor.insertElement("catalog", catUri);
    bodyCursor.toPrevToken();
    bodyCursor.insertElement("cd", catUri);
    bodyCursor.toPrevToken();
    bodyCursor.insertElementWithText("price", catUri, "11.90");
    
    

    String xpathString = "<catalog> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist>  <country>UK</country>  <company>CBS Records</company> <price>11.90</price>  <year>1988</year>  </cd>  </catalog>";
    //bodyCursor.insertChars(xpathString);
    bodyCursor.insertElementWithText(qname, value);
    bodyCursor.dispose();


    bodyCursor = envelopeDocument.getEnvelope().getBody().newCursor();
    String poUri = "http://openuri.org/easypo";
    bodyCursor.insertElement("purchase-order", poUri);
    bodyCursor.toPrevToken();
    bodyCursor.insertElement("line-item", poUri);
    
    addTopicInfo(envelopeDocument);
    bodyCursor.toPrevToken();
    bodyCursor.insertElementWithText("price", poUri, "300");
    bodyCursor.dispose();

    return envelopeDocument;
  }
    
  public SOAPMessage createSOAPMessage() {
    EnvelopeDocument envelopeDocument = createEnvelopeDocument();
    System.out.println(envelopeDocument.toString());
    /*
      EnvelopeDocument envelopeCopy=(EnvelopeDocument)envelopeDocument.copy();
      System.out.println(moduleName + "COPY OF THE EnvelopeDocument is \n" +
      envelopeCopy.toString());
    */

    SOAPMessage soapMessage = null;
    try {
      soapMessage =  soapEnvelopeConversion.getSOAPMessage(envelopeDocument);
    } catch (ProcessingException ex) {
      String errorReport ="Problems converting to javax.xml.SOAPMessage\n"
	+ ex.toString();
      System.out.println(errorReport);
    }
    
    return soapMessage;
  }



  public void sendSOAPMessage(SOAPMessage soapMessage, String sendTo) 
    throws Exception {
    URL sendToURL = new URL(sendTo);
    HttpURLConnection httpUrlConnection = (HttpURLConnection) sendToURL.openConnection(); 
    
    if (!httpUrlConnection.getDoOutput()) {
      httpUrlConnection.setDoOutput(true);  
    }
    
    httpUrlConnection.setDoInput(true); 
    httpUrlConnection.setRequestMethod("POST");
    httpUrlConnection.setRequestProperty("Content-Type","text/xml");
    httpUrlConnection.connect();
    OutputStream outputStream = httpUrlConnection.getOutputStream(); 
    
    /*URLConnection urlConnection = (URLConnection) sendToURL.openConnection();
      urlConnection.setDoOutput(true);
      urlConnection.setDoInput(true);
      OutputStream outputStream = urlConnection.getOutputStream();*/
    byte[] soapBytes = SoapMarshaller.marshallSoapMessage(soapMessage);

    //soapMessage.writeTo(outputStream);
    outputStream.write(soapBytes);
    outputStream.flush();
    outputStream.close();
    //printSoapMessage(soapMessage);
    System.out.println(moduleName + "Sent SOAP Message to [" +
		       sendToURL + "]");
    
    BufferedReader in = new BufferedReader(new 
      InputStreamReader( httpUrlConnection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)
      System.out.println(inputLine);
    

  }



  
  private void addTopicInfo(EnvelopeDocument envelopeDocument) {
    String topicName = "/Literature/Shakespere";
    QName qName = wseQNames.getTopicQNameNBX();
    boolean added = soapMessageAlteration.addToSoapHeader(envelopeDocument, 
							  qName, topicName);

    if (!added) {
      System.out.println(moduleName + "Addition of Topic info NOT Successful");
    }
  }

  public static void main(String[] args) {
    System.out.println("Runnin java cgl.narada.wsinfra.apps.SOAPClient");
    if (args.length != 2) {
      String errorReport = 
	"Usage: java cgl.narada.wsinfra.apps.SOAPClient " +
	"[WseSourceAddress] [WseSubManagerAddress]";
      System.out.println(errorReport);
      System.exit(0);
    }

    String sourceAddress = args[0];
    String wseSubManagerAddress = args[1];

    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok;
    String cmd;

    try {
      SOAPClient endpoint = 
	new SOAPClient(sourceAddress, wseSubManagerAddress);

      while (true) {
      	cmd = r.readLine();
	if (cmd == null) {
	  System.out.println("Terminating program ....");
	  break;
	}
	if(cmd.startsWith("h")) {
	  System.out.println("Send Data [from] [to] -> s  [sendTo]" );
	  System.out.println("Create SOAP Message   -> c  " );
	}

	if(cmd.startsWith("c")) {
	  SOAPMessage soapMessage = endpoint.createSOAPMessage();
	  RoleRetriever retriever = RoleRetriever.getInstance();
	  Enumeration e = retriever.retrieveRoles(soapMessage);
	  System.out.println("Retrieved Roles include \n");
	  while (e.hasMoreElements()) {
	    System.out.print(e.nextElement() + "   ");
	  }
	  
	}
	
	

	if (cmd.startsWith("s")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "s" */
	  String sendTo = tok.nextToken();
	  SOAPMessage soapMessage = endpoint.createSOAPMessage();
	  endpoint.sendSOAPMessage(soapMessage, sendTo);
	} 

	
      } /* end while(true) */

    }catch (Exception ioe) {
      ioe.printStackTrace();
    } /* end try-catch */
  }/*end main() */

}
